package cn.msqweb.controller;



import cn.msqweb.config.MyService;
import cn.msqweb.entity.SysMenu;
import cn.msqweb.model.Result;
import cn.msqweb.service.SysMenuService;
import cn.msqweb.util.AuthUtils;
import cn.msqweb.vo.MenuAndAuth;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 系统权限业务控制层
 */
@Api(tags = "系统权限接口管理")
@RequestMapping("sys/menu")
@RestController
public class SysMenuController {

    @Resource(name = "sysMenuService")
    private SysMenuService sysMenuService;

    @Resource
    private MyService myService;
    /**
     * 查询用户操作权限
     */
    @GetMapping("nav")
    public Result<MenuAndAuth> loadUserMenuAndAuth(){
        //当前用户id
        Long loginSysUserID = AuthUtils.getLoginSecurityUserID();

        Set<SysMenu> menus = ((SysMenuService) myService.getBeanByName("sysMenuService")).selectSysMenuListByUserID(loginSysUserID);

        //查询用户操作权限
        Set<String> loginSecurityUserPerms = AuthUtils.getLoginSecurityUserPerms();
        MenuAndAuth menuAndAuth = new MenuAndAuth(menus, loginSecurityUserPerms);
        return Result.success(menuAndAuth);
    }

    @ApiOperation("系统权限集合")
    @GetMapping("table")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result<List<SysMenu>> loadSysMenuList() {
        List<SysMenu> list = sysMenuService.list(new LambdaQueryWrapper<SysMenu>()
                .orderByDesc(SysMenu::getOrderNum));
        return Result.success(list);
    }
    @ApiOperation("新增系统权限")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result<String> saveSysMenu(@ApiParam("权限对象") @RequestBody SysMenu sysMenu) {
        boolean saved = sysMenuService.save(sysMenu);
        return Result.handler(saved);
    }
    @ApiOperation("根据标识查询权限详情")
    @GetMapping("info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:info')")
    public Result<SysMenu> loadSysMenuInfo(@ApiParam("权限标识") @PathVariable Long id) {
        SysMenu sysMenu = sysMenuService.getById(id);
        return Result.success(sysMenu);
    }

    @ApiOperation("修改权限信息")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result<String> modifySysMenuInfo(@ApiParam("权限对象") @RequestBody SysMenu sysMenu) {
        boolean updated = sysMenuService.updateById(sysMenu);
        return Result.handler(updated);
    }

    @ApiOperation("删除系统权限")
    @DeleteMapping("{menuId}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result<String> removeSysMenu(@ApiParam("权限标识") @PathVariable Long menuId) {
        Boolean removed = sysMenuService.removeSysMenu(menuId);
        return Result.handler(removed);
    }

}
